package cn.jihhhh.chatgpt.data.test;

import cn.jihhhh.chatglm.utils.BearerTokenUtils;
import cn.jihhhh.chatgpt.common.Constants;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.jihhhh.chatgpt.data.trigger.http.dto.ChatGPTRequestDTO;
import cn.jihhhh.chatgpt.data.trigger.http.dto.MessageEntity;
import cn.jihhhh.chatgpt.data.types.enums.ChatGPTModel;
import cn.jihhhh.chatgpt.domain.chat.ChatCompletionRequest;
import cn.jihhhh.chatgpt.domain.chat.ChatCompletionResponse;
import cn.jihhhh.chatgpt.domain.chat.Message;
import cn.jihhhh.chatgpt.session.OpenAiSession;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Charsets;
import lombok.extern.slf4j.Slf4j;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.CountDownLatch;

import static com.github.houbb.heaven.util.secrect.Md5Util.md5;

/**
 * @author jihhhh
 * @description 微信支付服务配置
 */
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApiTest {

    @Resource
    private OpenAiSession openAiSession;

    public static void main(String[] args) {
        Map<String, String> params = new HashMap<>();
        params.put("mch_id", "1705404082");

        params.put("out_trade_no", "LTZF2022113023096");
        params.put("total_fee", "0.05");
        params.put("body", "测试支付流程");
        String s = String.valueOf(System.currentTimeMillis() / 1000);
        params.put("timestamp", s);
        params.put("notify_url", "http://www.baidu.com");

        String sign = createSign(params, "f89957e30578378e709e11321fb89dd2");

        // 发送HTTP请求
        HttpResponse execute = HttpRequest.post("https://api.ltzf.cn/api/wxpay/native")
                .header("content-type", "application/x-www-form-urlencoded")
                .body("mch_id=1705404082&out_trade_no=LTZF2022113023096&total_fee=0.05&body=测试支付流程&timestamp=" + s
                        + "&notify_url=http://www.baidu.com&time_expire=15m&sign=" + sign).execute();
        String body = execute.body();
        System.out.println(execute.body());
    }

    protected static String packageSign(Map< String, String > params, boolean urlEncoder) {
        // 先将参数以其参数名的字典序升序进行排序
        TreeMap< String, String > sortedParams = new TreeMap < String, String > (params);
        // 遍历排序后的字典，将所有参数按"key=value"格式拼接在一起
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (Map.Entry< String, String > param: sortedParams.entrySet()) {
            String value = param.getValue();
            if (StringUtils.isBlank(value)) {
                continue;
            }
            if (first) {
                first = false;
            } else {
                sb.append("&");
            }
            sb.append(param.getKey()).append("=");
            if (urlEncoder) {
                try {
                    value = urlEncode(value);
                } catch (UnsupportedEncodingException e) {}
            }
            sb.append(value);
        }
        return sb.toString();
    }

    protected static String urlEncode(String src) throws UnsupportedEncodingException {
        return URLEncoder.encode(src, Charsets.UTF_8.name()).replace("+", "%20");
    }

    protected static String createSign(Map < String, String > params, String partnerKey) {
        // 生成签名前先去除sign
        params.remove("sign");
        String stringA = packageSign(params, false);
        String stringSignTemp = stringA + "&key=" + partnerKey;
        return md5(stringSignTemp).toUpperCase();
    }


    /**
     * 此对话模型 3.5 接近于官网体验
     */
    @Test
    public void test_chat_completions() {
        // 1. 创建参数
        ChatCompletionRequest chatCompletion = ChatCompletionRequest
                .builder()
                .messages(Collections.singletonList(Message.builder().role(Constants.Role.USER).content("写一个java冒泡排序").build()))
                .model(ChatCompletionRequest.Model.GPT_3_5_TURBO.getCode())
                .build();
        // 2. 发起请求
        ChatCompletionResponse chatCompletionResponse = openAiSession.completions(chatCompletion);
        // 3. 解析结果
        chatCompletionResponse.getChoices().forEach(e -> {
            log.info("测试结果：{}", e.getMessage());
        });
    }

    /**
     * 此对话模型 3.5 接近于官网体验 & 流式应答
     */
    @Test
    public void test_chat_completions_stream() throws JsonProcessingException, InterruptedException {
        // 1. 创建参数
        ChatCompletionRequest chatCompletion = ChatCompletionRequest
                .builder()
                .stream(true)
                .messages(Collections.singletonList(Message.builder().role(Constants.Role.USER).content("1+1").build()))
                .model(ChatCompletionRequest.Model.GPT_3_5_TURBO.getCode())
                .build();
        // 2. 发起请求
        EventSource eventSource = openAiSession.chatCompletions(chatCompletion, new EventSourceListener() {
            @Override
            public void onEvent(EventSource eventSource, String id, String type, String data) {
                log.info("测试结果：{}", data);
            }
        });
        // 等待
        new CountDownLatch(1).await();
    }

    @Test
    public void test_request_json() {

        List<MessageEntity> messages = new ArrayList<>();

//        MessageEntity messageEntity00 = new MessageEntity();
//        messageEntity00.setRole(Constants.Role.USER.getCode());
//        messageEntity00.setContent("你是一个非常专业的 Java 开发工程师，具备世界一流水平，曾在多家世界级互联网公司任职，可以写出非常优秀易于扩展和迭代的代码。");

        MessageEntity messageEntity01 = new MessageEntity();
        messageEntity01.setRole(Constants.Role.USER.getCode());
        messageEntity01.setContent("写一个java冒泡排序");

//        messages.add(messageEntity00);
        messages.add(messageEntity01);

        ChatGPTRequestDTO requestDTO = ChatGPTRequestDTO.builder().model(ChatGPTModel.GPT_3_5_TURBO.getCode()).messages(messages).build();

        log.info(JSON.toJSONString(requestDTO));
        // {"messages":[{"content":"你是一个非常专业的 Java 开发工程师，具备世界一流水平，曾在多家世界级互联网公司任职，可以写出非常优秀易于扩展和迭代的代码。","role":"user"},{"content":"写一个java冒泡排序","role":"user"}],"model":"gpt-3.5-turbo"}

        String str = "{\"messages\":[{\"content\":\"写一个java冒泡排序\",\"role\":\"user\"}],\"model\":\"gpt-3.5-turbo\"}";
    }

}
